//
//  AppDelegate.m
//  HuateVideo
//
//  Created by Tiger on 12-5-17.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import "JSON.h"
#import "VideoPlayerViewController.h"
#import "CommonWebServices.h"
#import "LocalVideo.h"
#import "Movie.h"
#import "TJSP.h"
#import "DataTools.h"
#import <AVFoundation/AVFoundation.h>
#import <AVFoundation/AVAsset.h>
#import "Cache.h"
#import "CacheManager.h"
#import "Reachability.h"
#import "UIImage+Scale.h"
#import "MySpaceViewController.h"
#import "UserLoginResponse.h"
@implementation MPMoviePlayerViewController(custom)
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft||interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
@end
@implementation UINavigationBar(CustomBackground)

- (UIImage *)barBackground
{
    if (self.tag >= 10000) {
		return nil;
	}
	else {
        return [UIImage imageNamed:@"top.png"];
	}
}

- (void)didMoveToSuperview
{
    //iOS5 only
    if ([self respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
    {
		[self setBackgroundImage:[self barBackground] forBarMetrics:UIBarMetricsDefault];
    }
}

- (void)drawRect:(CGRect)rect
{
    [[self barBackground] drawInRect:rect];
}

@end

@implementation AppDelegate
@synthesize tabbar;
@synthesize mydownloadViewController;
@synthesize downLoadedViewController;
@synthesize window = _window;

- (void)dealloc
{
    [localDic release];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:PLAYMOVIENOTIFICATION object:nil
     ];
    [downLoadedViewController release];
	[mydownloadViewController release];
    [_window release];
    [tabbar release];
    //[imagePicker release];
    [super dealloc];
}
//多语言设置

-(void)readLocalSetting{
    localDic=[[NSMutableDictionary alloc] init];
    NSString* localizedPath=[[NSBundle mainBundle] pathForResource:@"LocalizedString" ofType:@"json"];
    NSString* content=[NSString stringWithContentsOfFile:localizedPath encoding:NSUTF8StringEncoding error:nil];
    [localDic addEntriesFromDictionary:[content JSONValue]];
}
-(NSString*)localString:(NSString*)ZH_hans{
    if (LOCALSWITCH) {
        return ZH_hans;
    }else {
        NSString* weiwuer=[localDic valueForKey:ZH_hans];
        if ([weiwuer isKindOfClass:[NSString class]]&&weiwuer.length) {
            return weiwuer;
        }else {
            return ZH_hans;
        }
        
    }
    
}
#pragma mark audio
- (BOOL) ensureAudio
{
    
    // Registers this class as the delegate of the audio session (to get background sound)
    [[AVAudioSession sharedInstance] setDelegate: self];  
    
    // Set category
    NSError *categoryError = nil;
    if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&categoryError]) {
        NSLog(@"Audio session category could not be set"); 
        return NO;
    }
    
    // Activate session
    NSError *activationError = nil;
    if (![[AVAudioSession sharedInstance] setActive: YES error: &activationError]) {
        NSLog(@"Audio session could not be activated");
        return NO;
    }
    
    // Allow the audio to mix with other apps (necessary for background sound)
    UInt32 doChangeDefaultRoute = 1;
    AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
    
    return YES;
}
#pragma mark - AVAudioSessionDelegate

- (void) beginInterruption
{
    
}

- (void) endInterruption
{
    // Sometimes the audio session will be reset/stopped by an interruption
    [self ensureAudio];
}

- (void) inputIsAvailableChanged:(BOOL)isInputAvailable
{
    
}
-(void)autoLogin{
    [MySpaceViewController sharedInstance];
    NSString* useName=[UserDefaults objectForKey:USERNAME_STORE_KEY];
//    NSString* pwd=[UserDefaults objectForKey:PASSWORD_STORE_KEY];
    if (useName!=nil) {
//        CommonWebServices *webServ = [[CommonWebServices alloc] init];
//        webServ.delegate = self;
//        NSMutableDictionary *parma = [NSMutableDictionary dictionary];
//        [parma setValue:useName forKey:@"UserName"];
//        [parma setValue:pwd forKey:@"PassWord"];
//        [webServ startRequestWithMode:@"UserInfo" Action:@"UserLogin" Parma:parma Class:@"UserLoginResponse" RootXML:@"UserLoginResponse" resultIsArray:NO];
//        [webServ release];
        [[NSNotificationCenter defaultCenter] postNotificationName:USERLOGIN_ACTION object:useName];
    }
    

}
#pragma mark --
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self readLocalSetting];
    [self ensureAudio];
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
//    [self initUserPlayRecord];
	mydownloadViewController=[[DownLoadViewController alloc] init];
    downLoadedViewController=[[MyDownLoadViewController alloc] init];
    [self checkDataFolder];
    [self autoLogin];
    //[self checkVersion];
    
    self.window.backgroundColor = TOOLBAR_TINTCOLOR;
    [self initTabbar];
    
    [self addDefaultImage];
    
    if (![UserDefaults objectForKey:PLAY_SERIES_WHEN_WIFI]) {
        [UserDefaults setObject:@"NO" forKey:PLAY_SERIES_WHEN_WIFI];
    }
    if (![UserDefaults objectForKey:ALERT_WHEN_NET_CHANGE]) {
        [UserDefaults setObject:@"NO" forKey:ALERT_WHEN_NET_CHANGE];
    }
    
    //[self initCamera];
    [self initNotification];
    [self checkNet];
    [self.window makeKeyAndVisible];
    
    return YES;
}

- (void)clearAllCacheFromDisk{
	NSArray *array = [CacheManager queryAllFromCache];
	
	if (array!=nil && [array count]>0) {
		
		[CacheManager clearCache: 0];
		
		NSFileManager *fileManager = [NSFileManager defaultManager];
		int cnt = [array count];
		for (int i=0; i<cnt; i++) {
			Cache *cache = [array objectAtIndex: i];
			
			[fileManager removeItemAtPath: cache.cobject error: nil];
			
		}
	}
}

- (void)checkNet
{
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
    
    Reachability *hostReach = [[Reachability reachabilityWithHostName:@"www.baidu.com"] retain];
	[hostReach startNotifier];
}

- (void) reachabilityChanged: (NSNotification* )note
{
    if ([[UserDefaults objectForKey:ALERT_WHEN_NET_CHANGE] isEqualToString:@"NO"]) {
        return;
    }
    
	Reachability* curReach = [note object];
	
    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    switch (netStatus)
    {
        case NotReachable:
        {
            UIAlertView	*alertview = [[UIAlertView alloc] initWithTitle:LS(@"提示")  
                                                                message:LS(@"请检查网络连接和设置")
                                                               delegate:self 	
                                                      cancelButtonTitle:LS(@"确定")
                                                      otherButtonTitles:nil];		
            [alertview show];		
            [alertview release];
            break;
        }
            
        case ReachableViaWWAN:
        {
            UIAlertView	*alertview = [[UIAlertView alloc] initWithTitle:LS(@"提示")  
                                                                message:LS(@"您现在使用GPRS网络模式，请注意网络流量")
                                                               delegate:self 	
                                                      cancelButtonTitle:LS(@"确定")
                                                      otherButtonTitles:nil];		
            [alertview show];		
            [alertview release];
            break;
        }
        case ReachableViaWiFi:
        {
            UIAlertView	*alertview = [[UIAlertView alloc] initWithTitle:LS(@"提示")  
                                                                message:LS(@"您现在使用WIFI网络模式，不会产生GPRS流量，请放心使用")
                                                               delegate:self 	
                                                      cancelButtonTitle:LS(@"确定")
                                                      otherButtonTitles:nil];		
            [alertview show];		
            [alertview release];
            break;
        }
    }
}

- (void)checkDataFolder
{
    if (![[NSFileManager defaultManager] fileExistsAtPath:LOCAL_VIDEOS_PATH]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:LOCAL_VIDEOS_PATH withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:DOWNLOADED_VIDEOS_PATH]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:DOWNLOADED_VIDEOS_PATH withIntermediateDirectories:YES attributes:nil error:nil];
    }
}

- (void)checkVersion
{
    CommonWebServices *webServ = [[CommonWebServices alloc] init];
    webServ.delegate = self;
    [webServ startRequestWithMode:@"ClientInfo" Action:@"GetVersion" Parma:nil Class:@"Movie" RootXML:@"GetVersionResult" resultIsArray:NO];
    [webServ release];
}

- (void)onCommonWebServicesWithCustomClass:(id)object tag:(NSInteger)tag{
    NSLog(@"获取版本信息成功");
    if ([object isKindOfClass:[UserLoginResponse class]]) {
        UserLoginResponse *userLoginResponse = (UserLoginResponse *)object;
        if (userLoginResponse.UserLoginResult >= 1) {
            NSLog(@"%d 表示登陆成功,返回值为用户ID",userLoginResponse.UserLoginResult);
            [[NSNotificationCenter defaultCenter] postNotificationName:USERLOGIN_ACTION object:[UserDefaults objectForKey:USERNAME_STORE_KEY]];
        }
    }

}

- (void)onCommonWebServicesFaild
{
    NSLog(@"获取版本信息失败");
}

- (void)initNotification
{
    [[NSNotificationCenter defaultCenter] addObserver: self 
                                             selector: @selector(startCamera:) 
                                                 name: START_CAMERA_NOTIFICATION 
                                               object: nil ];
    
    [[NSNotificationCenter defaultCenter] addObserver: self 
                                             selector: @selector(startPhotoLibrary:) 
                                                 name: START_PHOTOLIBRARY_NOTIFICATION 
                                               object: nil ];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(startPlayMovie:)
                                                 name:PLAYMOVIENOTIFICATION 
                                               object:nil];
}

- (void)addDefaultImage
{
    UIImageView* defaultImageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Default.png"]];
    defaultImageView.tag=10086;
    defaultImageView.frame=CGRectMake(0, 20, 320, 460);
    UIImageView* animate=[[UIImageView alloc] initWithFrame:CGRectMake((320-32)/2, 360, 32, 32)];
    animate.animationImages=[NSArray arrayWithObjects:[UIImage imageNamed:@"01.png"],[UIImage imageNamed:@"02.png"],[UIImage imageNamed:@"03.png"],[UIImage imageNamed:@"04.png"], [UIImage imageNamed:@"05.png"],[UIImage imageNamed:@"06.png"],nil];
    animate.animationDuration=0.7;
    [defaultImageView addSubview:animate];
    [animate startAnimating];
    [animate release];
    [self.window addSubview:defaultImageView];
    [defaultImageView release];
}

- (void)deleteDefaultImage
{
    UIImageView* defaultImageView = (UIImageView *)[self.window viewWithTag:10086];
    [defaultImageView removeFromSuperview];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)initTabbar
{
    NSString *path = [[NSBundle mainBundle]pathForResource: @"Tabbar" ofType: @"json"];
    NSString *appListStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    
    SBJSON *json = [[SBJSON new] autorelease];
    NSArray *array = [NSArray arrayWithArray:[json objectWithString:appListStr error:nil]];
    
    NSMutableArray *controllers = [[NSMutableArray alloc]init];
    
    for (int i=0; i<[array count]; i++) {
		NSDictionary *dict = [array objectAtIndex: i];
		
		NSString *title = [dict objectForKey:@"title"];
		UIImage *icon = [UIImage imageNamed:[dict objectForKey: @"icon"]];
		NSString *controller = [dict objectForKey: @"controller"];
        
		Class currentElement_Class = NSClassFromString(controller);
		UIViewController *currentController = [[currentElement_Class alloc]init];
        currentController.title = LS(title);
		
		currentController.tabBarItem=[[UITabBarItem alloc] initWithTitle:LS(title) image:icon tag:i];
		UINavigationController *navControl = [[UINavigationController alloc]initWithRootViewController: currentController];
		navControl.navigationBar.tintColor = TOOLBAR_TINTCOLOR;
		[currentController release];
		
		[controllers addObject: navControl];
		[navControl release];
	}
    
    tabbar = [[CustomTabBarController alloc]initWithArray:array];
    tabbar.viewControllers = controllers;
    [tabbar setSelectedItemIndex:0];
	[self.window addSubview: tabbar.view];
	[controllers release];
}
#pragma  mark moviePlayerViewController
//- (void)initUserPlayRecord{
//	id var=[[NSUserDefaults standardUserDefaults] objectForKey:PlAYRECORDING_KEY];
//	if (var==nil) {
//		NSMutableArray*records=[[NSMutableArray alloc] init];
//		[[NSUserDefaults standardUserDefaults] setObject:records forKey:PlAYRECORDING_KEY];
//	}
//}
- (void)recordBeginPlaying:(id)dic{
	NSMutableArray* records=[UserDefaults objectForKey:PlAYRECORDING_KEY];
	if (records==nil) {
		records=[NSMutableArray array];
	}
	for (id mov in records) {
		if ([[mov News_id] isEqualToString:[dic News_id]]) {
			[records removeObject:mov];
			break;
		}
	}
	[records insertObject:dic atIndex:0];
	[UserDefaults setObject:records forKey:PlAYRECORDING_KEY];
	[[NSNotificationCenter defaultCenter] postNotificationName:REFRESHRECORD object:nil];

}
- (void)recordWhenFinishedPlay:(id)movie {
	NSMutableArray*records=[UserDefaults objectForKey:PlAYRECORDING_KEY];
	for (id mov in records) {
		if ([[mov News_id] isEqualToString:[movie News_id]]) {
			[mov setSecondPlayed:[movie secondPlayed]];
			break;
		}
	}
	[UserDefaults setObject:records forKey:PlAYRECORDING_KEY];

}
- (void)initMoviePlayer{
    //   VideoPlayerViewController* moviePlayerViewController=[[VideoPlayerViewController alloc] init];    
}

-(void)startPlayMovie:(NSNotification*)notify{

    id movie=[notify object];
	NSString *SrcUrl = @"";
    
    if ([movie isKindOfClass:[LocalVideo class]]) {
        if([[NSFileManager defaultManager] fileExistsAtPath:[movie storePath]]){
            SrcUrl = [movie storePath];	
        }
    }
    else {
        if ([[movie Type] intValue] == MovieChannelTypeSeries) {
            delePlay = movie;
        }
        else {
            if([[NSFileManager defaultManager] fileExistsAtPath:[movie storePath]]){
                SrcUrl = [movie storePath];	
            }
            else {
                SrcUrl = [movie File_path];
            }
        }
    }
    
	
	if (![movie isKindOfClass:[LocalVideo class]] && [[movie Type] intValue] == MovieChannelTypeSeries) {
		//电视剧 
        //每次播放电视剧时，对电视剧设置当前播放的集数，在详细信息页面和收藏、历史列面设置
        //暂时用[movie OrderNUM]表示当前正在播放的集数，从0开始
        //播放[movie storePath_array]集合，如果[movie storePath_array]对应的集数不存在则播放[movie File_path_array]
        //[[NSFileManager defaultManager] fileExistsAtPath:[[movie storePath_array] objectAtIndex:i]]
        //[[NSFileManager defaultManager] fileExistsAtPath:[[movie File_path_array] objectAtIndex:i]]
        
        NSString *storePath = nil;
        
        if ([movie OrderNUM] < [[movie File_path_array] count]) {
            if ([movie OrderNUM] < [[movie storePath_array] count]) {
                storePath = [[movie storePath_array] objectAtIndex:[movie OrderNUM]];
            }
            
            NSString *File_path = [[movie File_path_array] objectAtIndex:[movie OrderNUM]];
            
            if(storePath && [[NSFileManager defaultManager] fileExistsAtPath:storePath]){
                SrcUrl = storePath;	
            }
            else {
                SrcUrl = File_path;
            }
        }
        else {
            [self.window showAlert:LS(@"提示") message:LS(@"播放地址无效")];
            return;
        }
	}
	
	if ([SrcUrl length]<=3) {
		[self.window showAlert:LS(@"提示") message:LS(@"播放地址无效")];
		return;
	}
    
	NSURL *url;
	if ([SrcUrl hasPrefix:@"http"]) {
		url=[NSURL URLWithString:SrcUrl];
	}else {
		url=[NSURL fileURLWithPath:SrcUrl];
	}
    if (![movie isKindOfClass:[LocalVideo class]]) {
        [self recordBeginPlaying:movie];
    }
	

    MPMoviePlayerViewController *moviePlayerViewController=[[MPMoviePlayerViewController alloc] initWithContentURL:url];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(Moviefinished:) 
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:moviePlayerViewController.moviePlayer];
    [self.tabbar presentModalViewController:moviePlayerViewController animated:YES];
    [moviePlayerViewController release];
}

-(void)Moviefinished:(NSNotification*)notify{
    MPMoviePlayerController* player=(MPMoviePlayerController*)[notify object];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:player];
    //    [self.tabbar dismissMoviePlayerViewControllerAnimated];
    
    if ([[UserDefaults objectForKey:PLAY_SERIES_WHEN_WIFI] isEqualToString:@"YES"]) {
        if ([[delePlay Type] intValue] == MovieChannelTypeSeries) {
            
            if ([delePlay OrderNUM] < [delePlay CountNum]-1) {
                [delePlay setOrderNUM:1+[delePlay OrderNUM]];
                [[NSNotificationCenter defaultCenter] postNotificationName:PLAYMOVIENOTIFICATION object:delePlay];
                return;
            }
        }
    }
    
    [self.tabbar dismissModalViewControllerAnimated:YES];
}
#pragma mark --
- (void)initCamera
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.videoQuality = UIImagePickerControllerQualityTypeMedium;
    imagePicker.videoMaximumDuration = 60.0f*20.0;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = NO;
    //imagePicker.mediaTypes = [NSArray arrayWithObject:@"public.movie"];
    //imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
}

- (void)startCamera:(NSNotification *)notification
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.videoQuality = UIImagePickerControllerQualityTypeMedium;
    imagePicker.videoMaximumDuration = 60.0f*20.0;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = NO;
    
    NSArray *mediaTypes = [notification object];
    imagePicker.mediaTypes = mediaTypes;
    
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) 
	{
		imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
	}
	else {
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    [tabbar presentModalViewController:imagePicker animated:YES];
}

- (void)startPhotoLibrary:(NSNotification *)notification
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.videoQuality = UIImagePickerControllerQualityTypeMedium;
    imagePicker.videoMaximumDuration = 60.0f*20.0;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = NO;
    
    NSArray *mediaTypes = [notification object];
    imagePicker.mediaTypes = mediaTypes;
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [tabbar presentModalViewController:imagePicker animated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker 
{
    [picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"]){
        //[self performSelector:@selector(showBusy) withObject:nil afterDelay:0.1];
        
        UIImage *imagetemp = [info objectForKey:UIImagePickerControllerOriginalImage];
        UIImage *image = [[imagetemp autoCorrectOrientaion] scaleToSize:CGSizeMake(75*4, 95*4)];
        
        NSDate *date = [NSDate date];
        NSString *time = [DataTools stringOfDate:date formatString:@"yyyy-MM-dd HH:mm:ss"];
        NSString *name = [DataTools stringOfDate:date formatString:@"yyyyMMddHHmmss"];
        
        NSData *videoData = UIImageJPEGRepresentation(image,1.0);
        NSString *tempPath = [LOCAL_VIDEOS_PATH stringByAppendingFormat:@"/%@.png",name];
        
        BOOL success = [videoData writeToFile:tempPath atomically:NO];
        
        if (success) {
            LocalVideo *localVideo = [[LocalVideo alloc]init];
            localVideo.time = time;
            localVideo.storePath = tempPath;
            localVideo.image = image;
            localVideo.ok = 0;
            localVideo.size = [videoData length];
            localVideo.fileType = @"P";
            
            int value = (arc4random() % 8999) + 1000;
            localVideo.fileid = [NSString stringWithFormat:@"%@%d",[DataTools stringOfDate:date formatString:@"yyyyMMddHHmmssSSS"],value];
            localVideo.name = [NSString stringWithFormat:@"%@.png",name];
            
            if (LOCALSWITCH) {
                localVideo.webid = 14;
            }
            else {
                localVideo.webid = 20;
            }
            
            
            NSMutableArray *myVideo = (NSMutableArray *)[UserDefaults objectForKey:MY_VIDEOS_STORE_KEY];
            
            if (!myVideo) {
                myVideo = [[NSMutableArray alloc]init];
            }
            
            [myVideo insertObject:localVideo atIndex:0];
            [UserDefaults setObject:myVideo forKey:MY_VIDEOS_STORE_KEY];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:REFLASH_MY_VIDEOS_NOTIFICATION object: nil];
            [self performSelector:@selector(toImage) withObject:nil afterDelay:0.3];
            
            
            UIAlertView	*alertview = [[UIAlertView alloc] initWithTitle:LS(@"提示")  
                                                                message:LS(@"已加入到本地图片列表")
                                                               delegate:self 	
                                                      cancelButtonTitle:LS(@"确定")
                                                      otherButtonTitles:nil];		
            [alertview show];		
            [alertview release];
        }
        
        //[self stopBusy];
    }
    else if ([mediaType isEqualToString:@"public.movie"]){
        
        
        
        NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
        NSDate *date = [NSDate date];
        NSString *time = [DataTools stringOfDate:date formatString:@"yyyy-MM-dd HH:mm:ss"];
        NSString *name = [DataTools stringOfDate:date formatString:@"yyyyMMddHHmmss"];
        
        NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
        NSString *tempPath = [LOCAL_VIDEOS_PATH stringByAppendingFormat:@"/%@.mp4",name];
        
        BOOL success = [videoData writeToFile:tempPath atomically:NO];
        
        if (success) {
            NSMutableArray *myVideo = (NSMutableArray *)[UserDefaults objectForKey:MY_VIDEOS_STORE_KEY];
            
            if (!myVideo) {
                myVideo = [[NSMutableArray alloc]init];
            }
            
            LocalVideo *localVideo = [[LocalVideo alloc]init];
            localVideo.time = time;
            localVideo.storePath = tempPath;
            localVideo.image = [self getVideoImage:videoURL];
            localVideo.ok = 0;
            localVideo.fileType = @"V";
            
            int value = (arc4random() % 8999) + 1000;
            localVideo.fileid = [NSString stringWithFormat:@"%@%d",[DataTools stringOfDate:date formatString:@"yyyyMMddHHmmssSSS"],value];
            localVideo.name = [NSString stringWithFormat:@"%@.mp4",name];
            
            if (LOCALSWITCH) {
                localVideo.webid = 14;
            }
            else {
                localVideo.webid = 20;
            }
            
            localVideo.seconds = [self getVideoSeconds:videoURL];
            localVideo.size = [videoData length];
            
            [myVideo insertObject:localVideo atIndex:0];
            [UserDefaults setObject:myVideo forKey:MY_VIDEOS_STORE_KEY];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:REFLASH_MY_VIDEOS_NOTIFICATION object: nil];
            [self performSelector:@selector(toVideo) withObject:nil afterDelay:0.3];
            
            UIAlertView	*alertview = [[UIAlertView alloc] initWithTitle:LS(@"提示")  
                                                                message:LS(@"已加入到本地视频列表")
                                                               delegate:self 	
                                                      cancelButtonTitle:LS(@"确定")
                                                      otherButtonTitles:nil];		
            [alertview show];		
            [alertview release];
            
        }
    }
    else {
        UIAlertView	*alertview = [[UIAlertView alloc] initWithTitle:LS(@"提示")  
                                                            message:LS(@"保存视频失败")
                                                           delegate:self 	
                                                  cancelButtonTitle:LS(@"确定")
                                                  otherButtonTitles:nil];		
        [alertview show];		
        [alertview release];
    }
    
    [tabbar setSelectedItemIndex:2];
    
    [picker dismissModalViewControllerAnimated:YES];
}

- (void)toVideo
{
    [[NSNotificationCenter defaultCenter] postNotificationName:TO_MY_VIDEOS_NOTIFICATION object: nil];
}

- (void)toImage
{
    [[NSNotificationCenter defaultCenter] postNotificationName:TO_MY_IMAGES_NOTIFICATION object: nil];
}

- (void)showBusy
{
    UIActivityIndicatorView *progress = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:
                                        UIActivityIndicatorViewStyleWhiteLarge];
    progress.frame = CGRectMake(25, 20, 30, 30);
    progress.tag = 18898;
    progress.hidesWhenStopped = YES;
    progress.center = CGPointMake(160, 240);
    [self.window addSubview: progress];
    [progress release];
    [progress startAnimating];
}

- (void)stopBusy
{
    UIActivityIndicatorView *progress = (UIActivityIndicatorView *)[self.window viewWithTag:18898];
    [progress stopAnimating];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (UIImage *)getVideoImage:(NSURL *)movieURL
{
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    
    
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:movieURL options:opts];
    
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    generator.appliesPreferredTrackTransform = YES;
    generator.maximumSize = CGSizeMake(320, 480);
    
    NSError *error = nil;
    CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(10, 10) actualTime:NULL error:&error];
    UIImage *image = [UIImage imageWithCGImage: img];
    
    if (error != nil) {
        NSLog(@"Can not generate thumb from video, %@", error);
        return nil;
    }
    
    return image;
}

- (NSInteger)getVideoSeconds:(NSURL *)movieURL
{
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
                                                     forKey:AVURLAssetPreferPreciseDurationAndTimingKey];                    
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:movieURL options:opts];  
    NSInteger second = urlAsset.duration.value/urlAsset.duration.timescale;
    
    return second;
}

@end
